﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SharingCenter.Web.User.CurrentProfile
{
    using SharingCenter.Web.Shared;
    using SharingCenter.Web.Classes;
    public partial class Education : Classes.PageBase
    {
        protected void Page_Init(object sender, EventArgs e)
        {
            FormView1.ItemInserting += new FormViewInsertEventHandler(FormView1_ItemInserting);
            FormView1.ItemInserted += new FormViewInsertedEventHandler(FormView1_ItemInserted);
            ldsEducation.Inserted += new EventHandler<LinqDataSourceStatusEventArgs>(ldsEducation_Inserted);
            DataList1.ItemDeleted += new EventHandler<ListViewDeletedEventArgs>(DataList1_ItemDeleted);
        }

        void DataList1_ItemDeleted(object sender, ListViewDeletedEventArgs e)
        {
            if (e.Exception == null)
            {
                DataList1.DataBind();
            }
        }

        void ldsEducation_Inserted(object sender, LinqDataSourceStatusEventArgs e)
        {
            if (e.Exception != null)
            {
                Response.Write(e.Exception.Message);
                e.ExceptionHandled = true;
            }
        }

        void FormView1_ItemInserted(object sender, FormViewInsertedEventArgs e)
        {
            PageUpdated = true;
            //RefreshPage();
            DataList1.DataBind();
        }

        void FormView1_ItemInserting(object sender, FormViewInsertEventArgs e)
        {
            ldsEducation.Select = null;
            Guid guid = System.Guid.NewGuid();
            e.Values["EducationId"] = guid;
            
            // Prepare dates
            NumericDropDownList startYear = (NumericDropDownList)FormView1.FindControl("nddStartYear");
            NumericDropDownList startMonth = (NumericDropDownList)FormView1.FindControl("nddStartMonth");
            NumericDropDownList endYear = (NumericDropDownList)FormView1.FindControl("nddEndYear");
            NumericDropDownList endMonth = (NumericDropDownList)FormView1.FindControl("nddEndMonth");

            DateTime startDate = new DateTime(int.Parse(startYear.SelectedValue), int.Parse(startMonth.SelectedValue), 1);

            DateTime? endDate = null;
            if (endYear.SelectedValue != "" && endMonth.SelectedValue != "")
            {
                endDate = new DateTime(int.Parse(endYear.SelectedValue), int.Parse(endMonth.SelectedValue), 1);
            }
            e.Values["StartDate"] = startDate;
            e.Values["EndDate"] = endDate;
        }

        protected void btnSave_Load(object sender, EventArgs e)
        {
            ScriptManager.GetCurrent(this).RegisterAsyncPostBackControl((Control)sender);
        }
    }
}
